import { h5ShareConfig } from '@/services/public/h5';

//判断是否在微信中
export const isWechat = () => {
  // @ts-ignore
  const ua = window.navigator.userAgent.toLowerCase();
  // @ts-ignore
  if (ua.match(/micromessenger/i) == 'micromessenger') {
    return true;
  } else {
    return false;
  }
};

/**
 *  获取本地存储的第一次进入记录的url
 * @type {string}
 */
export const getBeforeUrl = () => {
  //@ts-ignore
  return window.BeforeUrl;
};

//初始化sdk配置
export const initJssdk = (callback: any) => {
  //服务端进行签名 ，可使用uni.request替换。 签名算法请看文档
  let url: any;
  const u: any = navigator.userAgent;

  if (u.indexOf('iPhone') > -1 && BUILD_ENV !== 'local') {
    url = getBeforeUrl();
    // url = window.location.href;
  } else {
    url = window.location.href;
  }
  console.log(url);

  h5ShareConfig({
    url: url,
  }).then((res) => {
    if (res.data.scalar) {
      wx.config(JSON.parse(res.data.scalar));
      //配置完成后，再执行分享等功能
      if (callback) {
        callback(res.data);
      }
    }
  });
};
//在需要自定义分享的页面中调用
export const share = (data: any = {}, surl: any = null) => {
  if (!isWechat()) {
    return;
  }
  // const url = surl ? surl : window.location.href;
  const url = surl ? surl : window.location.origin + '/pages/client/index';

  //每次都需要重新初始化配置，才可以进行分享
  initJssdk(() => {
    wx.ready(() => {
      const shareData = {
        title: data.title || '你好呀',
        desc: data.desc || '你好呀',
        link: url,
        imgUrl: data.img || 'https://www.ww.www/public/logo.jpg',
        success: function () {
          //用户点击分享后的回调，这里可以进行统计，例如分享送金币之类的
          console.log('分享成功');
        },
        cancel: function () {},
      };
      //分享给朋友接口
      wx.onMenuShareAppMessage(shareData);
      //分享到朋友圈接口
      wx.onMenuShareTimeline(shareData);

      // wx.hideAllNonBaseMenuItem();

      // wx.hideOptionMenu();
    });
  });
};
